﻿namespace DFGK.WMS.Common
{
    public static class GlobalManager
    {
        private static Dictionary<string, Dictionary<string, int>> AvgAllotDic
        {
            get; set;
        }
        public static string AvgAllot(string key, List<string> list)
        {
            if (list == null || list.Count == 0)
            {
                return null;
            }
            if (GlobalManager.AvgAllotDic == null)
            {
                GlobalManager.AvgAllotDic = new Dictionary<string, Dictionary<string, int>>();
            }
            //int key = list[0].StationSort.GetValueOrDefault();
            if (!GlobalManager.AvgAllotDic.ContainsKey(key) || GlobalManager.AvgAllotDic[key] == null)
            {
                GlobalManager.AvgAllotDic[key] = new Dictionary<string, int>();

            }
            List<string> allotAddrs = GlobalManager.AvgAllotDic[key].Keys.ToList();
            List<string> currAddrs = list.ToList();
            List<string> removeKeys = allotAddrs.Except(currAddrs).ToList();
            List<string> addKeys = currAddrs.Except(allotAddrs).ToList();

            if (removeKeys != null && removeKeys.Count > 0)
            {
                foreach (string removeKey in removeKeys)
                {
                    GlobalManager.AvgAllotDic[key].Remove(removeKey);
                }
            }
            if (addKeys != null && addKeys.Count > 0)//只要有变化，重新进行排序赋值
            {
                Dictionary<string, int> dic = new Dictionary<string, int>();
                foreach (string item in list)
                {
                    if (GlobalManager.AvgAllotDic[key].ContainsKey(item))
                    {
                        dic[item] = GlobalManager.AvgAllotDic[key][item];
                    }
                    else
                    {
                        dic[item] = 0;
                    }
                }
                GlobalManager.AvgAllotDic[key] = dic;
            }

            string currDestAddr = "";
            if (GlobalManager.AvgAllotDic[key].All(kv => kv.Value == 1))//中途变更，可能会进入改条件
            {
                currDestAddr = GlobalManager.AvgAllotDic[key].FirstOrDefault().Key;
            }
            else
            {
                currDestAddr = GlobalManager.AvgAllotDic[key].FirstOrDefault(kv => kv.Value == 0).Key;
            }
            GlobalManager.AvgAllotDic[key][currDestAddr] = 1;
            if (GlobalManager.AvgAllotDic[key].All(kv => kv.Value == 1))
            {
                GlobalManager.AvgAllotDic[key].Clear();
            }
            return list.Find(t => t == currDestAddr);
        }
    }
}
